package com.wishes.update;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import com.wishes.utils.UpdateChecker;
import org.apache.log4j.Logger;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

public class DownloadDialog extends JDialog {
    /**
     * log
     */
    private Logger logger = Logger.getLogger(DownloadDialog.class);

    private String downloadURL = "";

    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JLabel versionInfo;
    private JLabel message;
    private JLabel licence;

    public DownloadDialog() {
        //一些dialog相关的样式、位置设置
        this.setTitle("检测更新");
        this.setResizable(false);
        this.setLocation(300, 300);

        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(e -> onOK());

        buttonCancel.addActionListener(e -> onCancel());

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        //默认不能点更新按钮
        buttonOK.setEnabled(false);

        //显示前从网络查询数据
        new Thread(() -> queryUpdateInfo()).start();

        //show dialog
        this.pack();
        this.setVisible(true);
    }

    /**
     * 检测更新
     */
    public void queryUpdateInfo() {
        try {
            UpdateChecker.Version v = UpdateChecker.checkUpdate(UpdateChecker.CHECK_UPDATE_TYPE.AUTO);
            if (v != null) {
                //恢复按钮功能
                buttonOK.setEnabled(true);

                //有更新
                versionInfo.setText("检测更新： " + v.getVersion());
                message.setText("<html><body>更新内容： <br><br>" + v.getWhatNew()
                        .replaceAll("\n", "<br>") + "</body></html>");
                this.downloadURL = v.getDownloadURL();
            } else {
                this.setTitle("关于");
                //无更新
                UpdateChecker.Version current = UpdateChecker.getCurrentVersionInfo();
                versionInfo.setText("已更新到最新版： " + current.getVersion());
                message.setText("<html><body>&copy;&nbsp;Wishes丶&nbsp;<br>" +
                        "项目地址：&nbsp;<a href=''>Shimeji Project</a>" +
                        "</body></html>");
                //点击跳转
                message.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        try {
                            Runtime.getRuntime().exec("cmd.exe /c start " + "https://github.com/a1098832322/shimeji");
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }

            //许可证明
            licence.setText("<html><body>开源许可：&nbsp;<a href=''>Apache 2.0</a>" +
                    "</body></html>");
            //添加鼠标点击跳转事件
            licence.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    try {
                        Runtime.getRuntime().exec("cmd.exe /c start " + "http://www.apache.org/licenses/LICENSE-2.0.html");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            logger.error("显示检测更新弹窗失败！", e);
        }
    }

    private void onOK() {
        //下载
        new Thread(() -> {
            // 创建下载窗口
            DownloadWindow window = new DownloadWindow("下载更新");
            //创建下载进程
            try {
                UpdateChecker.download(window);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("下载失败！", e);
            }

        }).start();

        //关闭当前窗口
        this.dispose();
    }

    private void onCancel() {
        this.dispose();
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        contentPane = new JPanel();
        contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
        contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
        final Spacer spacer1 = new Spacer();
        panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false));
        panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        buttonOK = new JButton();
        buttonOK.setText("更新");
        panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        buttonCancel = new JButton();
        buttonCancel.setText("取消");
        panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new BorderLayout(0, 0));
        contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(230, 10), new Dimension(230, 200), new Dimension(230, 200), 0, false));
        versionInfo = new JLabel();
        versionInfo.setText("查询中...请稍后...");
        panel3.add(versionInfo, BorderLayout.NORTH);
        message = new JLabel();
        message.setText(" ");
        panel3.add(message, BorderLayout.CENTER);
        licence = new JLabel();
        licence.setText("Label");
        panel3.add(licence, BorderLayout.SOUTH);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPane;
    }
}
